#!/usr/bin/python3

from os import listdir, path
from re import search, IGNORECASE
from sys import argv

import pyglet
from pyglet.gl import *
from pyglet.window import key

def get_pic(d):
    return [name for name in listdir(d) if search('.bmp|.gif|.jpg|.jpeg|.png$', name, IGNORECASE)]

base_dir = path.abspath(path.dirname(argv[1]))
now = get_pic(base_dir).index(argv[1])
img = pyglet.image.load(path.join(base_dir, get_pic(base_dir)[now]))
img.anchor_x = img.width // 2
img.anchor_y = img.height // 2
win = pyglet.window.Window(width=400, height=300, resizable=True)
win.set_caption('%s(%dx%d)' % (get_pic(base_dir)[now], img.width, img.height))

@win.event
def on_draw():
    win.clear()
    img.blit(win.width // 2, win.height // 2)

@win.event
def on_key_press(symbol, modifiers):
    global img, now
    files = get_pic(base_dir)
    if symbol == key.LEFT:
        if now == 0:
            now = len(files) - 1
        else:
            now -= 1
    elif symbol == key.RIGHT:
        if now == len(files) - 1:
            now = 0
        else:
            now += 1
    elif symbol == key.ESCAPE:
        win.close()
        exit()
    img = pyglet.image.load(path.join(base_dir, files[now]))
    img.anchor_x = img.width // 2
    img.anchor_y = img.height // 2
    win.set_caption('%s(%dx%d)' % (files[now], img.width, img.height))

glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glClearColor(1, 1, 1, 1)
pyglet.app.run()
